package com.huang.controller;

import com.huang.dao.impl.UserDaoImpl;
import com.huang.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.stream.Collectors;

@Controller
public class UserController {

    @Resource
    UserDaoImpl userDao;

    @PostMapping(value = "/user/login")
    public String login(
            @RequestParam String username,
            @RequestParam String password,
            Model model
    ) {
        List<User> allUsers = userDao.getAllUsers();
        List<User> list = allUsers.stream().filter(user -> user.getUsername().equals(username) && user.getPassword().equals(password)).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(list)) {
            return "404-error";
        } else {
            model.addAttribute("username", username);
            return "my-account";
        }
    }

    @PostMapping(value = "/user/register")
    public String register(
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String email,
            Model model
    ) throws ParseException {
        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setGrander(1);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        user.setBirth(sdf.parse("2010-01-01"));
        userDao.saveUser(user);
        return "index";
    }


}
